<?php

namespace app\admin\model;

use app\admin\service\Rbac;
use app\common\enums\StatusEnum;

class Role extends \app\common\model\Role
{
    public static function getList($where)
    {
        $rbac = new Rbac();
        $return = $rbac->getRole($where);

        foreach ($return['data'] as $key => $value) {
            $return['data'][$key]['status'] = StatusEnum::getStatus($value['status']);
            $return['data'][$key]['create_time'] = get_datetime($value['create_time']);
        }
        return [
            'model' => $return['data'],
            'count' => count($return['data'])
        ];
    }

    /**
     * 获取状态正常的角色列表
     * @param bool $withPermissionId
     * @param int $userId
     * @return mixed
     */
    public static function getAllEnabled($withPermissionId = true, $userId = 0)
    {
        $rbac = new Rbac();
        $res = $rbac->getRole(['status' => StatusEnum::ENABLED], $withPermissionId);
        $role = $res['data'];

        if ($userId > 0 && !empty($role)) {
            // 获取用户对应的角色
            $userRole = UserRole::getColumnByUser($userId);
            foreach ($role as $key => $value) {
                $role[$key]['active'] = isset($userRole[$value['id']]) ? true : false;
            }
        }
        return $role;
    }

    /**
     * 更新角色权限
     * @param $data
     * @param $idsStr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function saveOne($data, $idsStr)
    {
        $rbac = new Rbac();
        if (!isset($data['id'])) {
            $data['create_time'] = time();
        }
        $res = $rbac->createRole($data, $idsStr);
        if ($res['code'] == 0) {
            if (isset($data['id']) && $data['id'] > 0) {
                // 查找该角色下面对应的管理员
                $userIds = UserRole::getColumnByRole($data['id']);
                foreach ($userIds as $userId => $roleId) {
                    // 重新缓存权限
                    $rbac = new Rbac();
                    $rbac->updatePermission($userId);
                }
            }
        }
        return $res;
    }

    public static function deleteData($ids)
    {
        $rbac = new Rbac();
        return $rbac->delRole($ids);
    }
}